﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SgAutoArchiveBrrDal;
using CmCaptureOcxLib;
using CmIDCardLib;
using System.IO;
using System.Globalization;
using System.Data.SqlClient;

namespace SgAutoArchiveSp.Dialog
{
    /// <summary>
    /// 登记页面
    /// </summary>
    public partial class Dialog_DJ : DevExpress.XtraEditors.XtraForm
    {
      
        ///private CmIDCardLib._DCmIDCard  axCmIDCard1;
        public T_CARDINFO _enCardInfo = null;
        private List<SgAutoArchiveBrrDal.T_ARCHIVETYPE> _listArchiveTypes;
        private  byte[] _cbuffer ;
        private byte[] _pbuffer;
        public Dialog_DJ()
        {
            InitializeComponent();

            cmb_PYSEX.SelectedIndex = 0;
            cmb_sonsex.SelectedIndex = 0;
            #region 使用回车跳转
            txt_Card.KeyDown += Txt_KeyDown;
            txt_Name.KeyDown += Txt_KeyDown;
            txt_Remark.KeyDown += Txt_KeyDown;

            #endregion

            _listArchiveTypes = SgAutoArchiveBrrDal.Linq.T_ARCHIVETYPE_Dal.Get_ARCHIVETYPEs();
            //if (_listArchiveTypes != null)
            //{
            //    foreach (var n in _listArchiveTypes)
            //    {
            //        cmb_CDType.Properties.Items.Add(n.TYPE_NAME);
            //    }
               
            //}
            //cmb_CDType.SelectedIndex = 0;
        }


        private void Txt_KeyDown(object sender, KeyEventArgs e)
        {
          
        }
        /// <summary>
        /// 登记按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Save_Click(object sender, EventArgs e)
        {
            try
            {
                if (txt_Card.Text == "")
                {
                    MessageBox.Show("请先登记身份信息");
                    return;
                }
                
                if (this.label23.Text=="")
                {
              
                    MessageBox.Show("请先进行人像采集！");
                    return;
                }
                string name = txt_Name.Text;
                string cardno = txt_Card.Text;
                var listno = SgAutoArchiveBrrDal.Linq.T_CARDINFO_Dal.Query_Cardno(cardno,1);
                if (listno.Count > 0)
                {
                    MessageBox.Show("请勿重复登记！");
                    return;
                }
                var listno2 = SgAutoArchiveBrrDal.Linq.T_CARDINFO_Dal.Query_Cardno(cardno, 2);
                if (listno2.Count > 0)
                {
                    MessageBox.Show("信息审核中！");
                    return;
                }
                string sex = txt_sex.Text;
                string date = txt_CSRQ.Text;
                string addr = txt_HJSZD.Text;
                string pcs = txt_SSPCS.Text;
                string yxrq = txt_YXQ.Text;
                string poname = txt_PYXM.Text;
                string pocardno = txt_PYSFZ.Text;
                string posex = cmb_PYSEX.Text;
                string podate = txt_PYCSRQ.Text;
                string fname = txt_fname.Text;
                string fno = txt_fcard.Text;
                string mname = txt_mname.Text;
                string mno = txt_mcard.Text;
                string sonname = txt_sonname.Text;
                string sonno = txt_soncard.Text;
                string sonsex = cmb_sonsex.Text;
                string sondate = txt_sondate.Text;
                string bcsm = txt_Remark.Text;

                //int.Parse(cmb_CDType.EditValue.ToString());
                //int typeid = -1;
                string typename = txt_typename.Text; //cmb_CDType.Text;
                if (typename == "")
                {
                    MessageBox.Show("请输入查档类型或查档事由！");
                    return;
                }
                //foreach(var nn in _listArchiveTypes)
                //{
                //    if(typename == nn.TYPE_NAME)
                //    {
                //        typeid = nn.TYPE_ID;
                //        break;
                //    }
                //}

                //if(typeid == -1)
                //{
                //    MessageBox.Show("请选择查档类型！");
                //    return;
                //}

                T_CARDINFO en = new T_CARDINFO();
                en.C_CARDNO = cardno;
                en.C_DATE = date;
                en.C_DEPARTMENT = pcs;
                en.C_DJDATE = DateTime.Now;
                en.C_FANAME = fname;
                en.C_FANO = fname;
                en.C_HJADDR = addr;
                en.C_MONAME = mname;
                en.C_MONO = mno;
                en.C_NAME = name;
                if (podate != "")
                {
                    en.C_PODATE = Convert.ToDateTime(podate);
                }
                en.C_PONAME = poname;
                en.C_PONO = pocardno;
                en.C_POSEX = posex;
                en.C_SEX = sex;
                if (sondate != "")
                {
                    en.C_SONDATE = Convert.ToDateTime(sondate);
                }
                en.C_YXDATE = yxrq;
                en.C_SONNAME = sonname;
                en.C_SONNO = sonno;
                en.C_SONSEX = sonsex;
                en.C_STAUTS = 1; //1登记 2 审批中 3结束
                en.C_I01 = 0;//-1 未通过 0未审核 1审核通过 2查阅结束
                en.C_V02 = bcsm;
                en.C_UNAME = SgArchiveCommons.commons._uname;
                //en.C_TYPEID = typeid;
                en.C_TYPENAME = typename;
                en.C_CBMP = _cbuffer;
                en.C_PIMG = _pbuffer;
                SgAutoArchiveBrrDal.Linq.T_CARDINFO_Dal.Add_TCARDINFO(en);
                MessageBox.Show("登记成功！");
                _enCardInfo = en;
                label23.Text = "";
                this.Dispose();
                this.Close();
                //frm_Main f = new frm_Main();
                //f.gridView_init();
            }
            catch { MessageBox.Show("登记失败！");
              
            }
        }

        public void PictureToBinaryStream(string fullPath)
        {    //获取当前程序运行路径    
           // string path = Application.StartupPath;
            //拼接成测试图片路径           
           // fullPath = Program._imagePath+"\\"+txt_Card+"\\证件.bmp";
           // string fullpat2 = Program._imagePath + "\\" + txt_Card + "\\人像.jpg";
            //初始化类    
            Bitmap bmp = new Bitmap(Image.FromFile(fullPath));
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            ms.Flush();            //将二进制数据存到byte数字中    
            byte[] bmpBytes = ms.ToArray();     
            string _bytes = Convert.ToBase64String(bmpBytes);
            foreach (var item in bmpBytes)
            {
                //richTextBox1.Text += item;
            }
            pictureBox1.Image = Image.FromStream(new MemoryStream(bmpBytes));
        }  
        
       
           
            

        private void Dialog_DJ_Load(object sender, EventArgs e)
        {
            
            // TODO: 这行代码将数据加载到表“sgAutoArchiveBrrDataSet.T_ARCHIVETYPE”中。您可以根据需要移动或删除它。
            /////this.t_ARCHIVETYPETableAdapter.Fill(this.sgAutoArchiveBrrDataSet.T_ARCHIVETYPE);
            
        }


        /// <summary>
        /// 打开摄像头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            try
            {
               int i = axCmCaptureOcx1.Initial();
                string  index = System.Configuration.ConfigurationSettings.AppSettings["index"];
                 i = int.Parse(index);
                //初始化
                //if (i == -2)
                //{
                //    MessageBox.Show("未连接摄像头");
                //}
                //if (comboBox1.Text == "人像拍摄")
                //{
                //    i = 2;
                //}
                //if (comboBox1.Text == "电脑拍摄")
                //{
                //    i = 1;
                //}
                //if (comboBox1.Text == "高拍仪拍摄")
                //{
                //    i = 0;
                //}
                //axCmCaptureOcx1.StartRun(i);
               //axCmCaptureOcx1.StartRun(1);//开启视频
                axCmCaptureOcx1.StartRun(i);
                
            }
            catch { MessageBox.Show("摄像头启动失败！"); }
        }


        /// <summary>
        /// 读取身份证信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                int i = axCmIDCard1.OpenUSBPort();
                string path = System.Windows.Forms.Application.StartupPath + "\\imagecard.bmp";
                if (File.Exists(path))
                    File.Delete(path);
                axCmIDCard1.SetHeadPicPath(path);
                axCmIDCard1.ReadIDCard();//读卡
                txt_Name.Text = axCmIDCard1.GetName();                 //读取用户名                                                   //读取用户性别
                if (axCmIDCard1.GetName() != "")
                {
                    txt_sex.Text = axCmIDCard1.GetSex();  // Cstring UserNation =  axCmIDCard1.GetNation();             //读取用户国籍
                    txt_CSRQ.Text = axCmIDCard1.GetBirthDate();       //读取用户出生日期
                    txt_HJSZD.Text = axCmIDCard1.GetAddr();                 //读取用户住址
                    txt_Card.Text = axCmIDCard1.GetID();                     //读取用户身份证号
                    txt_SSPCS.Text = axCmIDCard1.GetOffice();             //读取用户身份证签发机关
                    txt_YXQ.Text = axCmIDCard1.GetBeginDate().ToString() + "-" + axCmIDCard1.GetEndDate().ToString(); //读取用户身份证起始有效期
                    string oldStr = path;
                    // 新文件名
                    string newStr = Program._imagePath + "\\" + txt_Card.Text + "证件.bmp";
                    if (File.Exists(newStr))
                    {
                        // File.Delete(newStr);
                        //20181215
                        pictureBox1.Load(newStr);
                        FileStream stream = new FileStream(newStr, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                        _cbuffer = new byte[stream.Length];
                        stream.Read(_cbuffer, 0, (int)stream.Length);
                        stream.Close();
                        axCmIDCard1.CloseUSBPort();
                    }
                    else
                    {
                        // 改名方法
                        FileInfo fi = new FileInfo(oldStr);
                        fi.MoveTo(Path.Combine(newStr));
                         pictureBox1.Load(newStr);
                        FileStream stream = new FileStream(newStr, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                        _cbuffer = new byte[stream.Length];
                        stream.Read(_cbuffer, 0, (int)stream.Length);
                        stream.Close();
                        axCmIDCard1.CloseUSBPort();
                    }



                }
                else
                {
                    MessageBox.Show("未检测到身份证");
                }
            }
            catch { MessageBox.Show("未读取到身份证信息"); }

        }

       /// 111

        /// <summary>
        /// 采集人像信息  保存路径为bin/image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            try
            { //拍摄图片
                if (txt_Card.Text == "")
                {
                    MessageBox.Show("请先登记身份信息");
                    axCmCaptureOcx1.EndVideo();
                    return;
                }
                string newStr = Program._imagePath + "\\" + txt_Card.Text + "人像.jpg";
                if (File.Exists(newStr))
                {
                    File.Delete(newStr);
                    axCmCaptureOcx1.SetImageColorMode(0);        //设置颜色模式0彩色/1灰度/2黑白
                    axCmCaptureOcx1.SetJpgQuanlity(100);               //设置图像质量0-100（若为BMP图像则不需要此步骤）
                    axCmCaptureOcx1.CaptureImage(newStr);
                    this.label23.Text = "人像信息采集完成！";
                    this.label23.Visible = false;
                    MessageBox.Show("人像信息采集完成！");
                    axCmCaptureOcx1.EndVideo();
                    FileStream stream = new FileStream(newStr, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    // FileStream stream = new FileStreamfile;
                    _pbuffer = new byte[stream.Length];
                    stream.Read(_pbuffer, 0, (int)stream.Length);
                    stream.Close();
                    return;

                }
                else
                {
                    axCmCaptureOcx1.SetImageColorMode(0);        //设置颜色模式0彩色/1灰度/2黑白
                    axCmCaptureOcx1.SetJpgQuanlity(100);               //设置图像质量0-100（若为BMP图像则不需要此步骤）
                    axCmCaptureOcx1.CaptureImage(newStr);
                    this.label23.Text = "人像信息采集完成！";
                    this.label23.Visible = false;
                    MessageBox.Show("人像信息采集完成！");
                    axCmCaptureOcx1.EndVideo();
                    FileStream stream = new FileStream(newStr, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    // FileStream stream = new FileStreamfile;
                    _pbuffer = new byte[stream.Length];
                    stream.Read(_pbuffer, 0, (int)stream.Length);
                    stream.Close();
                    return;

                }
            }
            catch { MessageBox.Show("采集人像失败！"); }
            axCmCaptureOcx1.EndVideo();
        }

        private void close(object sender, FormClosedEventArgs e)
        {
           
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            PictureToBinaryStream(Program._imagePath+"\\1.bmp");
        }

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {

 
            FileStream stream = new FileStream(Program._imagePath + "\\" + "1.bmp", System.IO.FileMode.Open, System.IO.FileAccess.Read);
            _cbuffer = new byte[stream.Length];
            stream.Read(_cbuffer, 0, (int)stream.Length);
            stream.Close();


        }
        private void insertcbmp(string path)
        {
            FileStream stream = new FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)stream.Length);
            stream.Close();
           // string strName = System.IO.Path.GetFileNameWithoutExtension(path);
           // SqlCommand cmd = new SqlCommand("Insert into Temp(name,photo) values(@name,@image)", sqlConn);
            //cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = strName;
            //cmd.Parameters.Add("@image", SqlDbType.Image).Value = buffer;
            //cmd.ExecuteNonQuery();
        }
        private void simpleButton5_Click(object sender, EventArgs e)
        {

            FileStream stream = new FileStream(Program._imagePath + "\\" + "1.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
            // FileStream stream = new FileStreamfile;
            _pbuffer = new byte[stream.Length];
            stream.Read(_pbuffer, 0, (int)stream.Length);
            stream.Close();
            this.label23.Text = "1";
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}